package com.hxbd.test.handles;


import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
//import java.util.function.Function;
//import java.util.function.ToDoubleFunction;
//import java.util.function.ToIntFunction;
//import java.util.function.ToLongFunction;
import java.util.Set;

import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.testng.Assert;
import org.testng.IReporter;
import org.testng.IResultMap;
import org.testng.ISuite;
import org.testng.ISuiteListener;
import org.testng.ISuiteResult;
import org.testng.ITestContext;
import org.testng.ITestResult;
import org.testng.xml.XmlSuite;

import com.duan.test.utils.Excel.DefaultExcelParser;
import com.duan.test.utils.Excel.FileUtils;
import com.duan.test.utils.Excel.IExcelParser;
import com.duan.test.utils.common.CommonUtils;
import com.hxbd.test.Beans.ReportBean;
import com.hxbd.test.Beans.TestDicBean;
import com.hxbd.test.utils.PlatformUtil;
import com.hxbd.test.utils.webdriver.HtmlUnit;

/**
 * testNG测试结构监听类：用于生成自定义的html报告
 */
public class NewReportListener implements IReporter, ISuiteListener {
	private static final String TESTRESULT_PATH = "testresult_path";
	private static final String separator = System.getProperty("file.separator");
	int PassNum = 0;
	int FailNum = 0;
	int SkipNum = 0;
	private long starttime;
	private long endtime;
	private static final String tomcat_path = "tomcat_path";
	private static final String Remote_APCHE_ADD = "remote_apache_add";
	private static final String TEST_DESCRIPTION = "test_description";

	@Override
	public void generateReport(List<XmlSuite> xmlSuites, List<ISuite> suites,
			String outputDirectory) {
		List<ITestResult> list = new ArrayList<ITestResult>();
		generateDic();
		generateTree();
		for (ISuite suite : suites) {
			Map<String, ISuiteResult> suiteResults = suite.getResults();
			for (ISuiteResult suiteResult : suiteResults.values()) {
				ITestContext testContext = suiteResult.getTestContext();
				IResultMap passedTests = testContext.getPassedTests();
				IResultMap failedTests = testContext.getFailedTests();
				IResultMap skippedTests = testContext.getSkippedTests();
				IResultMap failedConfig = testContext.getFailedConfigurations();
				PassNum += passedTests.size();
				FailNum += failedTests.size();
				SkipNum += skippedTests.size();
				list.addAll(this.listTestResult(passedTests));
				list.addAll(this.listTestResult(failedTests));
				list.addAll(this.listTestResult(skippedTests));
				list.addAll(this.listTestResult(failedConfig));
			}
		}
		// this.sort(list);
		List<ReportBean> ResultList = ConvertTestResult(list);
		String Content = GeneralReport(list, ResultList);
		this.outputResult(Content, outputDirectory + "/NewReport.html");
	}

	private ArrayList<ITestResult> listTestResult(IResultMap resultMap) {
		Set<ITestResult> results = resultMap.getAllResults();
		return new ArrayList<ITestResult>(results);
	}

	// private void sort(List<ITestResult> list){
	// Collections.sort(list, new Comparator<ITestResult>() {
	// @Override
	// public int compare(ITestResult r1, ITestResult r2) {
	// if(r1.getStartMillis()>r2.getStartMillis()){
	// return 1;
	// }else{
	// return -1;
	// }
	// }
	// });
	// }
//	private void sort(List<ITestResult> list) {
//		Collections.sort(list, new Comparator<ITestResult>() {
//			@Override
//			public int compare(ITestResult r1, ITestResult r2) {
//				// TODO Auto-generated method stub
//				if (r1.getStartMillis() > r2.getStartMillis()) {
//					return 1;
//				} else {
//					return -1;
//				}
//			}
//		});
//	}

	private void outputResult(String Content, String path) {
		File f = new File(path);
		if (f.exists())
			f.delete();
		try {
			BufferedWriter output = new BufferedWriter(new FileWriter(f));
			output.write(Content);
			output.flush();
			output.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	public List<ReportBean> ConvertTestResult(List<ITestResult> list) {
		List<ReportBean> ResultList = new ArrayList<ReportBean>();
		Object[][] Objs;
		try {
			Objs = getData(new File(CommonUtils
					.getFilePath("")).getParent()+"/surefire-reports/ScriptDictionary.xls");
			for (int i = 1; i < Objs.length; i++) {
				ReportBean rep = new ReportBean();
				for (int j = 0; j <= 2; j++) {
					if (CommonUtils.isStrEmpty(Objs[i][j].toString())) {
						Assert.fail("测试覆盖字典ScriptDictionary.xls第" + (i + 1)
								+ "行第" + (j + 1) + "列数据为空，不允许");
					}
				}
				rep.setScriptName(Objs[i][0].toString());
				rep.setModuelName(Objs[i][1].toString());
				rep.setTestName(Objs[i][2].toString());
				rep.setPageName(Objs[i][3].toString());				
				ResultList.add(rep);
			}
			// 生成report.xls供自动化平台使用(这段代码基于平台使用必须保存，不能更改。)
			String reportDesc = FileUtils.getParentFolder(CommonUtils.getFilePath(""))+"/surefire-reports/testReport.xls";
			FileUtils f = new FileUtils();
			f.createFolder(FileUtils.getParentFolder(CommonUtils.getFilePath(""))+"/surefire-reports");
			FileUtils.copyFile(
					CommonUtils.getFilePath("TestData/testReport.xls"),
					reportDesc, true);
			IExcelParser iep = DefaultExcelParser.createExcelParser(reportDesc);
			FileOutputStream fileoutputstream = new FileOutputStream(reportDesc);
			String classname = "";
			String method = "";
			String resultstr = null;
			String suite = "";
			String testname = "";
			int count = 0;
			// 测试报告改进
			for (int i = 0; i < ResultList.size(); i++) {
				long time = 0L;
				BigInteger tmp = new BigInteger("1");
				for (ITestResult result : list) {

					if (result
							.getTestClass()
							.getRealClass()
							.getName()
							.equalsIgnoreCase(
									ResultList.get(i).getScriptName().trim())
							&& ResultList.get(i).getTestName().trim()
									.equalsIgnoreCase(result.getName())) {
						time = time
								+ (result.getEndMillis() - result
										.getStartMillis());
						classname = result.getTestClass().getRealClass()
								.getName();
						suite = result.getTestContext().getSuite().getName();
						testname = result.getTestContext().getName();
						if (this.getStatus(result.getStatus())
								.equals("FAILURE")) {
							tmp = tmp.multiply(new BigInteger("0"));
						} else if (this.getStatus(result.getStatus()).equals(
								"SKIP")) {
							// tmp *= 3;
							tmp = tmp.multiply(new BigInteger("3"));
						} else if (this.getStatus(result.getStatus()).equals(
								"SUCCESS")) {
							// tmp *= 2;
							tmp = tmp.multiply(new BigInteger("2"));
						}
					} else if (result
							.getTestClass()
							.getRealClass()
							.getName()
							.equalsIgnoreCase(
									ResultList.get(i).getScriptName().trim())
							&& ResultList.get(i).getTestName().isEmpty()) {
						time = time
								+ (result.getEndMillis() - result
										.getStartMillis());
						classname = result.getTestClass().getRealClass()
								.getName();
						suite = result.getTestContext().getSuite().getName();
						testname = result.getTestContext().getName();
						ResultList.get(i).setTimeSpan(
								(ResultList.get(i).getTimeSpan() == null
										|| ResultList.get(i).getTimeSpan()
												.isEmpty() ? 0 : Long
										.parseLong(ResultList.get(i)
												.getTimeSpan())
										+ (result.getEndMillis() - result
												.getStartMillis()))
										+ "");
						if (ResultList.get(i).getResult() == null) {
							ResultList.get(i).setResult(
									this.getStatus(result.getStatus()));
						} else {
							if (ResultList.get(i).getResult().equals("FAILURE")
									|| this.getStatus(result.getStatus())
											.equals("FAILURE")) {
								ResultList.get(i).setResult("FAILURE");
							} else if (ResultList.get(i).getResult()
									.equals("SKIP")
									|| this.getStatus(result.getStatus())
											.equals("SKIP")) {
								ResultList.get(i).setResult("SKIP");
							} else {
								ResultList.get(i).setResult("SUCCESS");
							}
						}

					}
				}
				ResultList.get(i).setTimeSpan(time + "毫秒 ");
				if (tmp.equals(BigInteger.ONE)) {

				} else if (tmp.equals(BigInteger.ZERO)) {
					ResultList.get(i).setResult("FAILURE");
				} else if (tmp.mod(new BigInteger("3")).intValue() == 0) {
					ResultList.get(i).setResult("SKIP");
				} else if (tmp.mod(new BigInteger("2")).intValue() == 0) {
					ResultList.get(i).setResult("SUCCESS");
				}
				resultstr = ResultList.get(i).getResult();
				method = ResultList.get(i).getTestName().trim();
				if (resultstr != null) {
					iep.writeInTemplate("report", classname, count + 1, 0);
					iep.writeInTemplate("report", method, count + 1, 1);
					iep.writeInTemplate("report", resultstr, count + 1, 2);
					iep.writeInTemplate("report", Long.toString(time),
							count + 1, 3);
					iep.writeInTemplate("report", suite, count + 1, 4);
					iep.writeInTemplate("report", testname, count + 1, 5);
					iep.writeInTemplate("report", ResultList.get(i)
							.getPageName(), count + 1, 6);
					iep.writeInTemplate("report", ResultList.get(i)
							.getFucPoint(), count + 1, 7);
					count++;
				}
			}
			iep.getWorkBook().write(fileoutputstream);
			fileoutputstream.close();

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return ResultList;
	}

	/**
	 * 生成html报告
	 * 
	 * @param list
	 * @param ResultList
	 * @return String
	 */
	public String GeneralReport(List<ITestResult> list,
			List<ReportBean> ResultList) {
		String MainContent = readTxtFile(CommonUtils
				.getFilePath(PageElementHandler.getStoreSettingProperties()
						.getProperty("SendMail_DIRECTORY")));

		// @CaseTotal@ @SuccessCount@ @FailedCount@ @OtherCount@
		int CaseTotal = 0;
		int SuccessCount = 0;
		int FailedCount = 0;
		int OtherCount = 0;
		String CaseDetail = "";
		for (int i = ResultList.size() - 1; i >= 0; i--) {
			if (ResultList.get(i).getResult() == null
					|| ResultList.get(i).getResult().isEmpty()) {
				ResultList.remove(i);
			}
		}
		List<String> newList = new ArrayList<String>();
		List<String> newList2 = new ArrayList<String>();
		Map<String, Integer> map = new HashMap<String, Integer>();
		Map<String, Integer> map2 = new HashMap<String, Integer>();
		for (int i = 0; i < ResultList.size(); i++) {
			if (!ResultList.get(i).getModuelName().equals("")) {
				newList.add(ResultList.get(i).getModuelName());
			}
		}
		for (int i = 0; i < ResultList.size(); i++) {
			if (!ResultList.get(i).getPageName().equals("")) {
				newList2.add(ResultList.get(i).getPageName());
			}
		}
		Iterator<String> iter = newList.iterator();
		while (iter.hasNext()) {
			int count = 0;
			String name = iter.next();
			while (newList.contains(name)) {
				iter.remove();
				count += 1;
				if (newList.contains(name)) {
					iter.next();
				}
			}
			map.put(name, count);
		}
		Iterator<String> iter2 = newList2.iterator();
		while (iter2.hasNext()) {
			int count = 0;
			String name = iter2.next();
			while (newList2.contains(name)) {
				iter2.remove();
				count += 1;
				if (newList2.contains(name)) {
					iter2.next();
				}
			}
			map2.put(name, count);
		}
		for (int i = 0; i < ResultList.size(); i++) {
			if (ResultList.get(i).getResult().equals("SUCCESS")) {
				SuccessCount++;
			}
			if (ResultList.get(i).getResult().equals("FAILURE")) {
				FailedCount++;
			}
			if (ResultList.get(i).getResult().equals("SKIP")) {
				OtherCount++;
			}
			CaseTotal++;
		}
		for (String key : map.keySet()) {
			Boolean isFirst = true;
			for (int j = 0; j < ResultList.size(); j++) {
				if (ResultList.get(j).getModuelName().equals(key)) {
					if (isFirst) {
						CaseDetail += "<tr><td rowspan=" + map.get(key) + ">"
								+ key + "</td>";
						isFirst = false;
					} else {
						CaseDetail += "<tr>";
					}
					Iterator<Entry<String, Integer>> iter3 = map2.entrySet()
							.iterator();
					while (iter3.hasNext()) {
						Entry<String, Integer> entry = iter3.next();
						String entrykey = entry.getKey();
						if (ResultList.get(j).getPageName().equals(entrykey)) {
							CaseDetail += "<td rowspan="
									+ entry.getValue().intValue() + ">"
									+ entrykey + "</td>";
							iter3.remove();
						}
					}
					CaseDetail += "<td>" + ResultList.get(j).getFucPoint()
							+ "</td><td>"
							+ TransTimeSpan(ResultList.get(j).getTimeSpan())
							+ "</td><td><font color=\""
							+ getColor(ResultList.get(j).getResult()) + "\">"
							+ ResultList.get(j).getResult()
							+ "</font></td></tr>";
				}
			}
		}
		String FailFunction = "<br/>";
		for (int i = 0; i < list.size(); i++) {
			if (list.get(i).getStatus() == 2) {
				FailFunction += list.get(i).getTestName() + ":"
						+ list.get(i).getMethod().getMethodName() + "<br/>";
			}
		}

		// @CaseTotal@
		MainContent = MainContent.replace("@CaseTotal@", CaseTotal + "");
		// @SuccessCount@
		MainContent = MainContent.replace("@SuccessCount@", SuccessCount + "");
		// @FailedCount@
		MainContent = MainContent.replace("@FailedCount@", FailedCount + "");
		// @OtherCount@
		MainContent = MainContent.replace("@OtherCount@", OtherCount + "");
		// CaseDetail
		MainContent = MainContent.replace("@CaseDetail@", CaseDetail);
		// testEnv
		MainContent = MainContent.replace("@testEnv@", PlatformUtil.getTestEnv());
		// reporturl
		MainContent = MainContent.replaceAll("\\$\\{EXTENTX_ADD\\}",PageElementHandler.getStoreSettingPropertie("EXTENTX_ADD"));
		MainContent = MainContent.replaceAll("\\$\\{TEST_DESCRIPTION\\}",PageElementHandler.getStoreSettingPropertie(TEST_DESCRIPTION));		
		String ip = "";
		try {
			ip = InetAddress.getLocalHost().getHostAddress();
		} catch (UnknownHostException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		String tmpstr = PageElementHandler.getStoreSettingPropertie(TESTRESULT_PATH) + PlatformUtil.getTesttype() + "test_"+PlatformUtil.getTestEnv()+"/testResult/"+CommonUtils.now("yyyyMMddHHmmss")+"/";

		HtmlUnit.createNewExtentHtml(FileUtils.getParentFolder(CommonUtils.getFilePath(""))+"/surefire-reports/", "ExtentReport.html", "ExtentNewReport.html");
		FileUtils  fu = new FileUtils();
		String os = System.getProperty("os.name");  
		String reporturl = "";
		if(os != null &&  os.toLowerCase().startsWith("win")){ 
			String tmppath = FileUtils.getRootFolder(new File(CommonUtils.getFilePath("")))+tmpstr;
			reporturl = "file://"
					+ ip + "/" + tmppath +"ExtentNewReport.html";
			fu.createFile(FileUtils.getParentFolder(CommonUtils.getFilePath(""))+"/surefire-reports/resultfilepath.txt", tmppath,"UTF-8");

		}  
		else if (os != null && os.toLowerCase().indexOf("linux") > -1) {
			reporturl = PageElementHandler.getStoreSettingPropertie(Remote_APCHE_ADD) + "/"+tmpstr+"ExtentNewReport.html";
			fu.createFile(FileUtils.getParentFolder(CommonUtils.getFilePath(""))+"/surefire-reports/resultfilepath.txt", PageElementHandler.getStoreSettingPropertie(tomcat_path )+tmpstr,"UTF-8");
		}
		MainContent = MainContent.replace("@reporturl@", reporturl);
		// @CurrentDate@
		SimpleDateFormat dateFormat = new SimpleDateFormat(
				"yyyy/MM/dd HH:mm:ss");
		MainContent = MainContent.replace("@CurrentDate@",
				dateFormat.format(new Date()));
		String totalTimes = TransTimeSpan(String.valueOf(endtime - starttime)
				+ "毫秒");
		MainContent = MainContent.replace("@totalTime@", totalTimes);
		String reportDesc = FileUtils.getParentFolder(CommonUtils.getFilePath(""))+"/surefire-reports/testReport.xls";
		IExcelParser iep = DefaultExcelParser.createExcelParser(reportDesc);
		try {
			Workbook wk = iep.getWorkBook();
			Sheet sheet = iep.getSheet(wk, "report");
			final int lastRowNum = sheet.getLastRowNum();
			FileOutputStream fileoutputstream = new FileOutputStream(reportDesc);
			iep.writeInTemplate("report", "total:" + CaseTotal, lastRowNum + 1,
					0);
			iep.writeInTemplate("report", "pass:" + SuccessCount,
					lastRowNum + 1, 1);
			iep.writeInTemplate("report", "fail:" + FailedCount,
					lastRowNum + 1, 2);
			iep.writeInTemplate("report", "totaltimes:" + totalTimes,
					lastRowNum + 1, 3);
			wk.write(fileoutputstream);
			fileoutputstream.close();
			System.out.println("输出测试结果完毕");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		// FailFunction
		// MainContent = MainContent.replace("@FailFunction@", FailFunction);
		return MainContent;
	}

	private String getStatus(int status) {
		String statusString = null;
		switch (status) {
		case 1:
			statusString = "SUCCESS";
			break;
		case 2:
			statusString = "FAILURE";
			break;
		case 3:
			statusString = "SKIP";
			break;
		default:
			break;
		}
		return statusString;
	}

	private String formatDate(long date) {
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return formatter.format(date);
	}

	public String getColor(String Result) {
		String Color = null;
		if (Result.equals("SUCCESS")) {
			Color = "green";
		} else if (Result.equals("FAILURE")) {
			Color = "red";
		} else {
			Color = "#ff9933";
		}
		return Color;
	}

	public String TransTimeSpan(String TimeSpan) {
		long Time = 0;
		long Second = 0;
		long Minute = 0;
		long Hour = 0;
		String iReturn = "";
		TimeSpan = TimeSpan.substring(0, TimeSpan.trim().length() - 2);
		try {
			Time = Integer.parseInt(TimeSpan);
			Second = Time / 1000;
			if (Second == 0) {
				Second = 1;
			}
			if (Second >= 60) {
				Minute = Second / 60;
				Second = Second % 60;
				if (Minute >= 60) {
					Hour = Minute / 60;
					Minute = Minute % 60;
				}
			}
			iReturn = (Hour == 0 ? "" : Hour + "时")
					+ (Minute == 0 ? "" : Minute + "分")
					+ (Second == 0 ? "" : Second + "秒");

		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return iReturn;
	}

	/**
	 * 生成测试报告的日志
	 * 
	 * @param notes
	 * @param result
	 * @param testResult
	 * @return String
	 */
	public String reportNotes(String notes, ITestResult result,
			String testResult) {
		notes += "###############################dataprovider-"
				+ result.getAttribute("invonum")
				+ "###############################" + "\r\n";
		Object[] o = result.getParameters();
		String parameters = "";
		for (int j = 0; j < o.length; j++) {
			parameters += "parameter#" + (j + 1) + " : " + o[j].toString()
					+ "\r\n";
		}
		notes += parameters + "\r\n";
		notes += "TestResult:" + testResult + "\r\n" + "\r\n";
		if (testResult.equalsIgnoreCase("FAILURE")) {
			StackTraceElement[] st = result.getThrowable().getStackTrace();
			String stacktraces = "";
			for (int j = 0; j < st.length; j++) {
				stacktraces += st[j].toString() + "\r\n";
			}
			notes += "EXCEPTION:" + "\n" + result.getThrowable().toString()
					+ "\r\n" + stacktraces + "\r\n";
		}
		return notes;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.testng.ISuiteListener#onStart(org.testng.ISuite)
	 */
	@Override
	public void onStart(ISuite suite) {
		// TODO Auto-generated method stub
		starttime = System.currentTimeMillis();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.testng.ISuiteListener#onFinish(org.testng.ISuite)
	 */
	@Override
	public void onFinish(ISuite suite) {
		// TODO Auto-generated method stub
		
		endtime = System.currentTimeMillis();
	}

	/**
	 * 读取TXT文件
	 * 
	 * @param filePath
	 */
	public static String readTxtFile(String filePath) {
		String iReturn = "";
		try {
			String encoding = "UTF-8";
			File file = new File(filePath);
			if (file.isFile() && file.exists()) { // 判断文件是否存在
				InputStreamReader read = new InputStreamReader(
						new FileInputStream(file), encoding);// 考虑到编码格式
				BufferedReader bufferedReader = new BufferedReader(read);
				String lineTxt = null;
				while ((lineTxt = bufferedReader.readLine()) != null) {
					// System.out.println(lineTxt);
					iReturn += lineTxt;
				}
				read.close();
			} else {
				System.out.println("找不到指定的文件");
			}
		} catch (Exception e) {
			System.out.println("读取文件内容出错");
			e.printStackTrace();
		}
		return iReturn;
	}

	/**
	 * 获得sheet对应数据
	 * 
	 * @param sheetname
	 *            表名
	 * @return 二维数据的数据对象
	 */
	public Object[][] getData(String filename) {
		Workbook wb;
		Sheet sheet;
		IExcelParser excelParser = DefaultExcelParser
				.createExcelParser(filename);
		Object[][] tempData = null;
		try {
			wb = excelParser.getWorkBook();
			if (null == wb) {
				tempData = null;
			}
			// get the first sheet
			sheet = excelParser.getSheet(wb, 0);
			if (null == sheet) {
				Assert.fail("Excel中没有sheet");
			}
			tempData = convertSheet2Array(sheet, excelParser);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			Assert.fail("Excel读取失败,请确认excel文件路径是否正确");
		}
		return tempData;
	}

	/**
	 * Description: convert sheet data.
	 * 
	 * @param sheet
	 *            表名
	 * @return Object[][] 对象数组 ;没有数据返回null
	 */
	private static Object[][] convertSheet2Array(Sheet sheet,
			IExcelParser excelParser) {
		int rows = sheet.getLastRowNum() + 1;
		int cols = sheet.getRow(0).getLastCellNum();
		// locate the last valid row
		for (; rows >= 0; rows--) {
			if (excelParser.getCellValue(sheet, rows - 1, 0).trim().length() != 0) {
				break;
			}
		}

		if (rows < 1) {
			return null;
		}

		// locate the last valid column
		for (; cols >= 0; cols--) {
			if (excelParser.getCellValue(sheet, 0, cols - 1).trim().length() != 0) {
				break;
			}
		}
		if (cols < 1) {
			return null;
		}

		Object[][] datas = new Object[rows][cols];

		for (int i = 0; i < rows; i++) {
			for (int j = 0; j < cols; j++) {
				String value = excelParser.getCellValue(sheet, i, j);
				if (value == null) {
					value = "";
				}
				if (value.equalsIgnoreCase("Y")) {
					datas[i][j] = Boolean.TRUE;
				} else if (value.equalsIgnoreCase("N")) {
					datas[i][j] = Boolean.FALSE;
				} else {
					datas[i][j] = value;
				}
			}
		}
		// 以下代码去除空行
		List<Object[]> list = new ArrayList<Object[]>();
		for (Object[] objs : datas) {
			Boolean isDel = true;
			for2: for (Object o : objs) {
				if (o != null) {
					isDel = isDel && false;
					break for2;
				}
			}
			if (!isDel) {
				list.add(objs);
			}
		}
		Object[][] datass = new Object[list.size()][cols];
		for (int i = 0; i < list.size(); i++) {
			datass[i] = list.get(i);
		}
		return datass;
	}
	
	public static void generateDic () {
		int count = 0;		
		String dicdesc = new File(CommonUtils
				.getFilePath("")).getParent()+separator+"surefire-reports"+separator+"ScriptDictionary.xls";
		FileUtils f = new FileUtils();
		f.createFolder(new File(CommonUtils
				.getFilePath("")).getParent()+separator+"surefire-reports");
		System.out.println("==========this is a test===========");
		System.out.println("目录:"+CommonUtils.getFilePath("TestData" + separator +"ScriptDictionary.xls"));
		FileUtils.copyFile(
				CommonUtils.getFilePath("TestData"+separator+"ScriptDictionary.xls"),
				dicdesc, true);
		IExcelParser iep = DefaultExcelParser.createExcelParser(dicdesc);
		try {
			Workbook wk = iep.getWorkBook();
			FileOutputStream fileoutputstream = new FileOutputStream(dicdesc);
			String sheet1name = wk.getSheetName(0);
			for (TestDicBean dicbean : PlatformUtil.getDicset()) {
				iep.writeInTemplate(sheet1name, dicbean.getClassname(), count + 1,
						0);
				iep.writeInTemplate(sheet1name, dicbean.getClassdetail(), count + 1,
						1);
				iep.writeInTemplate(sheet1name, dicbean.getMethodname(), count + 1,
						2);
				iep.writeInTemplate(sheet1name, dicbean.getInterfacedetail(), count + 1,
						3);
				count++;
			}
			wk.write(fileoutputstream);
			fileoutputstream.close();
			System.out.println("生成测试用例字典完毕");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static void generateTree () {
		int count = 0;	
		int count2 = 1;
		Map<String,String> m = new HashMap<String, String>();
		Set<String> s = new HashSet<String>();
		Map<String,Integer> map = new HashMap<String, Integer>();
		String dicdesc = new File(CommonUtils
				.getFilePath("")).getParent()+separator+"surefire-reports"+separator+"testMenu.xls";
		FileUtils f = new FileUtils();
		f.createFolder(new File(CommonUtils
				.getFilePath("")).getParent()+separator+"surefire-reports");
		System.out.println(CommonUtils.getFilePath("TestData"+separator+"testMenu.xlsx"));
		FileUtils.copyFile(
				CommonUtils.getFilePath("TestData"+separator+"testMenu.xlsx"),
				dicdesc, true);
		IExcelParser iep = DefaultExcelParser.createExcelParser(dicdesc);
		try {
			Workbook wk = iep.getWorkBook();
			FileOutputStream fileoutputstream = new FileOutputStream(dicdesc);
			String sheet1name = wk.getSheetName(0);
			iep.writeInTemplate(sheet1name, "node1", 1,
					0);
			iep.writeInTemplate(sheet1name, "1", 1,
					1);
			iep.writeInTemplate(sheet1name, CommonUtils.getFilePath(PageElementHandler.getStoreSettingPropertie(TESTRESULT_PATH))+"test", 1,
					3);
			iep.writeInTemplate(sheet1name, "TRUE", 1,
					5);
			for (TestDicBean dicbean : PlatformUtil.getDicset()) {
				String casedetail = dicbean.getClassdetail();			
				if (!s.contains(casedetail)) {
					s.add(casedetail);	
					iep.writeInTemplate(sheet1name, "node"+(count+2), count + 2,
							0);
					String key = "1_"+count2;
					m.put(casedetail, key);
					map.put(casedetail, 0);
					iep.writeInTemplate(sheet1name, key, count + 2,
							1);
					iep.writeInTemplate(sheet1name, "1", count + 2,
							2);
					iep.writeInTemplate(sheet1name, casedetail, count + 2,
							3);
					count2++;
					count++;
				}
				else {
					iep.writeInTemplate(sheet1name, "node"+(count+2), count + 2,
							0);
					iep.writeInTemplate(sheet1name, m.get(casedetail)+"_"+(map.get(casedetail)+1), count + 2,
							1);
					map.put(casedetail, map.get(casedetail)+1);
					iep.writeInTemplate(sheet1name, m.get(casedetail), count + 2,
							2);
					iep.writeInTemplate(sheet1name, dicbean.getInterfacedetail(), count + 2,
							3);
					count++;
				}
			}
			wk.write(fileoutputstream);
			fileoutputstream.close();
			System.out.println("生成测试树完毕");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}